///////////////////////////////////////////////////////////////
// Copyright(c) BeingStudio
// 
// FileName : InterlockedVariable
// Creator  : ChenShiCai
// E-Mail   : BeingStudio@GMail.com
// Date     : 2008-05-31
// Comment  : 
//
///////////////////////////////////////////////////////////////

#ifndef _INCLUDE_INTERLOCKEDVARIABLE_H_
#define _INCLUDE_INTERLOCKEDVARIABLE_H_

#ifdef WIN32

#include <windows.h>

#else 
////////////////////////////////////////////////////////////////////////////////////////////////////
// @berief : increments (increases by one) the value of the specified 32-bit variable, The function 
//           prevents more than one thread from using the same variable simultaneously
// @param pValue : [in][out] Pointer to the variable to be incremented
// @return : the resulting incremented value.
// @remark :The variable pointed to by the parameter must be aligned on a 32-bit boundary; 
//          otherwise, this function will fail on multiprocessor x86 systems and any non-x86 systems.
////////////////////////////////////////////////////////////////////////////////////////////////////
inline long InterlockedIncrement(long *plValue)
{
    long lResult;
    __asm__ __volatile__
    (
        "movl $0x01, %%eax\n"    
        "lock xaddl %%eax, (%1)\n"
        "incl %%eax\n"
        :    
            "=a"(lResult)
        : 
            "c"(plValue)
        :
            "memory"			
    );
    return lResult;
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// @berief : decrements (decreases by one) the value of the specified 32-bit variable, The function 
//           prevents more than one thread from using the same variable simultaneously
// @param pValue : [in][out] Pointer to the variable to be decremented
// @return : the resulting decremented value.
// @remark :The variable pointed to by the parameter must be aligned on a 32-bit boundary; 
//          otherwise, this function will fail on multiprocessor x86 systems and any non-x86 systems.
////////////////////////////////////////////////////////////////////////////////////////////////////
inline long InterlockedDecrement(long *plValue)
{
    long lResult;
    __asm__ __volatile__
    (
        "movl $0xffffffff, %%eax\n"    
        "lock xaddl %%eax, (%1)\n"
        "decl %%eax\n"
        :    
            "=a"(lResult)
        : 
            "c"(plValue)
        :
            "memory"			
    );
    return lResult;
}
#endif // WIN32

#endif //_INCLUDE_INTERLOCKEDVARIABLE_H_
